package com.nuoniu.sibanyun.mapper.provider;

import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.common.stream.Iterables;
import com.nuoniu.sibanyun.entity.crm.CrmCustomer;
import com.nuoniu.sibanyun.entity.dto.DynamicConditionDto;
import com.nuoniu.sibanyun.entity.dto.DynamicDto;
import com.nuoniu.sibanyun.userThread.DataScope;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.apache.ibatis.jdbc.SQL;

import java.sql.Array;
import java.sql.PreparedStatement;
import java.util.*;

/**
 * @ClassName CrmDynamicConditionProvider
 * @Description TODO
 * @Authpr baiqiang
 * @Date 2020/6/22 18:20
 **/
public class CrmDynamicConditionProvider {

    /**客户基本信息**/
    final private String CUSTOMER_TABLE = "pub_customer crm";
    /**联系人信息**/
    final private String LINKMAN_TABLE = "crm_linkman linkMan";
    /**联系记录**/
    final private String TOUCH_TABLE = "crm_touch touch";
    /**商机**/
    final private String BUSINESS_TABLE = "crm_business business";
    /**用户收藏记录**/
    final private String COLLECT_TABLE = "crm_collect collect";
    /**市场活动**/
    final private String ACTIVITY_TABLE = "crm_activity activity";
    /**财务信息**/
    final private String FINANCE_TABLE = "crm_finance_info finance";




    final private String LINKMAN_TABLE_JOIN = CUSTOMER_TABLE + " ON crm.id = linkMan.crm_id AND linkMan.status = 0 ";

    final private String TOUCH_TABLE_JOIN = CUSTOMER_TABLE + " ON crm.id = touch.crm_id AND touch.status = 0 ";

    final private String TOUCH_LEFT_JOIN_LINKMAN = LINKMAN_TABLE + " ON linkMan.id = touch.link_man_id ";

    final private String BUSINESS_TABLE_JOIN = CUSTOMER_TABLE + " ON business.crm_id = crm.id AND business.status = 0 ";

    final private String BUSINESS_JOIN_ACTIVITY = ACTIVITY_TABLE + " ON activity.id = business.activity_id AND activity.status = 0 ";

    final private String COLLECT_TABLE_JOIN = COLLECT_TABLE + " ON crm.id = collect.customer_id and collect.collect_user_id = #{dynamicDto.userId} ";

    final private String FINANCE_TABLE_JOIN = CUSTOMER_TABLE + " ON crm.id = finance.crm_id AND finance.status = 0 ";


    final private String ID_FIELD = "Id";
    final private String NAME_FIELD = "Name";

    /**
     * 动态拼接SQL
     * @param dynamicDto
     * @return
     */
    public String crmDynamicConditionSql(DynamicDto dynamicDto) {
        SQL sql = new SQL();
        select(sql,dynamicDto);
        return  sql.toString();
    }

    private void select(SQL sql ,DynamicDto dynamicDto){
        UserInfo userInfo = UserThreadLocal.get();
        Integer joinBusinessType = dynamicDto.getJoinBusinessType();
        List<DynamicConditionDto> joinTableConditions = dynamicDto.getJoinTableConditions();
        String crmType = dynamicDto.getCrmType();
        DataScope dataScope = userInfo.getDataScope();
        List<DynamicConditionDto> dtos = dynamicDto.getDtos();
        String companyType = dynamicDto.getCompanyType();
        Set<String> selectSet =  new HashSet<>();
        Set<String> leftJoinTable = new HashSet<>();
        Set<String> fromTable = new HashSet<>();
        Set<String> whereSet = new HashSet<>();
        List<Boolean> isCollect = new ArrayList<>();
        DynamicConditionDto myDto = new DynamicConditionDto();

//        Iterables.forEach(dtos, (index, item) -> {
        /** 动态条件 组合*/
        dtos.stream().forEach(item->{
            Integer dataType = item.getDataType(); //数据类型 1.基础 2.完全自定义 3.继承 4.继承自定义"
            Object[] rangDateVal = item.getRangDateVal();
            String type = item.getType();
            String value = item.getValue();
            value = StringUtils.trim(value);
            boolean valueNotBlank = StringUtils.isNotBlank(value);

            if(item.getCode() != null && item.getCode().equals("isCollected")) {
                if(valueNotBlank) {
                    if(value.equals("是")) {
                        isCollect.add(true);
                    } else {
                        isCollect.add(false);
                    }
                }

                return;
            }

            if(dataType == 3 || dataType == 4){
                String parentCode = item.getParentCode();
                String[] split = parentCode.split("_");
                String table = split[0];
                String code = split[1];
                String uncamelCase = StringUtils.uncamelCase(code);

                if(dataType == 4){
                    Integer parentId = item.getParentId();
                    selectSet.add(table + ".define_fields AS "+ table +"_defineFields");
                    if(valueNotBlank){
                        if("文本".equals(type) || "区域".equals(type) || "快速文本".equals(type) ){
                            whereSet.add(table +".define_fields-> '$.\""+ parentId +"\"' LIKE CONCAT('%',#{paramMap."+parentCode+"},'%')");
                        }else{
                            whereSet.add(table +".define_fields-> '$.\""+ parentId +"\"' = #{paramMap."+parentCode+"}");
                        }
                    }else if(("时间".equals(type) ) && null != rangDateVal && rangDateVal.length == 2 ){
                        ArrayList rangDate = (ArrayList)rangDateVal[1];
                        String startDate = String.valueOf(rangDate.get(0));
                        String endDate =String.valueOf(rangDate.get(1));
                        if(StringUtils.isNoneBlank(startDate)){
                            whereSet.add(table +".define_fields-> '$.\""+ parentId +"\"' >= #{paramMap."+parentCode+"_startDate}");
                        }
                        if(StringUtils.isNoneBlank(endDate)){
                            whereSet.add(table +".define_fields-> '$.\""+ parentId +"\"' <#{paramMap."+parentCode+"_endDate}");
                        }
                    }
                    else if(("日期".equals(type)) && null != rangDateVal && rangDateVal.length == 2 ){
                        ArrayList rangDate = (ArrayList)rangDateVal[1];
                        String startDate = String.valueOf(rangDate.get(0));
                        String endDate =String.valueOf(rangDate.get(1));
                        if(StringUtils.isNoneBlank(startDate)){
                            whereSet.add(table +".define_fields-> '$.\""+ parentId +"\"' >= #{paramMap."+parentCode+"_startDate}");
                        }
                        if(StringUtils.isNoneBlank(endDate)){
                            whereSet.add(table +".define_fields-> '$.\""+ parentId +"\"' <=#{paramMap."+parentCode+"_endDate}");
                        }
                    }
                    return;
                }
                if("shareType".equals(code)){
                    selectSet.add(table +".share_user_name AS shareUserName");
                    selectSet.add(table +".share_user_id AS shareUserId");
                    selectSet.add(table +".collar_user_id AS collarUserId");
                    selectSet.add(table +".collar_user_name AS collarUserName");

                }
                //替换操作
                if("搜索选择".equals(type) || "查询下拉".equals(type)){
                    String nameField = idFieldToNameField(code);
                    String parentNameField = idFieldToNameField(parentCode);

                    String uncamelCaseName = StringUtils.uncamelCase(nameField);
                    if(StringUtils.isBlank(uncamelCaseName)){
                        uncamelCaseName = uncamelCase;
                    }
                    selectSet.add(table +"."+ uncamelCaseName +" as "+ parentNameField);
                    selectSet.add(table +"."+ uncamelCase +" as "+ parentCode);
                }else{
                    selectSet.add(table +"."+ uncamelCase +" AS "+ parentCode);
                }
                leftJoinTable.add(table);
                if(valueNotBlank){
                    if("文本".equals(type) || "区域".equals(type)|| "快速文本".equals(type) ){
                        whereSet.add(table +"."+ uncamelCase +" LIKE CONCAT('%',#{paramMap."+parentCode+"},'%')");
                    }else if("是否".equals(type)) {
                        if("false".equals(value)){
                            whereSet.add("("+table +"."+ uncamelCase +" = '0' OR " +table +"."+ uncamelCase +" IS NULL)");
                        }else{
                            whereSet.add(table +"."+ uncamelCase +" = '1'");
                        }
                    }else if("shareType".equals(code)) {
                        //共享状态
                        if("共享".equals(value)){
                            String shareSql = "(crm.share_type = 1 AND FIND_IN_SET(" + userInfo.getUserId() + ",crm.share_user_id)";
                            //查询分享的模块
                            if(StringUtils.isNotBlank(dynamicDto.getType())){
                                shareSql += " AND  FIND_IN_SET(#{dynamicDto.type},crm.share_menu)";
                            }
                            shareSql += " AND ( crm.share_end = 1 OR crm.share_time > NOW()) )";
                            whereSet.add(shareSql);

                        }else if("未共享".equals(value)){
                            String shareSql = "crm.share_type != 1";
                            whereSet.add(shareSql);
                        }
                    }
                    else if("搜索选择".equals(type)){
                        whereSet.add(table +"."+ uncamelCase +" IN (${paramMap."+parentCode+"})");
                    }
                    else{
                        whereSet.add(table +"."+ uncamelCase +" = #{paramMap."+parentCode+"}");
                    }
                }else if(("时间".equals(type) ) &&  null != rangDateVal && rangDateVal.length == 2 ){
                    ArrayList rangDate = (ArrayList)rangDateVal[1];
                    String startDate = String.valueOf(rangDate.get(0));
                    String endDate =String.valueOf(rangDate.get(1));
                    if(StringUtils.isNoneBlank(startDate)){
                        whereSet.add(table +"."+ uncamelCase +" >= #{paramMap."+parentCode+"_startDate}");
                    }
                    if(StringUtils.isNoneBlank(endDate)){
                        whereSet.add(table +"."+ uncamelCase +" < #{paramMap."+parentCode+"_endDate}");
                    }
                }else if(("日期".equals(type)) &&  null != rangDateVal && rangDateVal.length == 2 ){
                    ArrayList rangDate = (ArrayList)rangDateVal[1];
                    String startDate = String.valueOf(rangDate.get(0));
                    String endDate =String.valueOf(rangDate.get(1));
                    if(StringUtils.isNoneBlank(startDate)){
                        whereSet.add(table +"."+ uncamelCase +" >= #{paramMap."+parentCode+"_startDate}");
                    }
                    if(StringUtils.isNoneBlank(endDate)){
                        whereSet.add(table +"."+ uncamelCase +" <= #{paramMap."+parentCode+"_endDate}");
                    }
                }

            }else if(dataType == 1){
                String source = item.getSource();
                fromTable.add(source);
                if("company".equals(source) || "vendor".equals(source) || "crm".equals(source) || "financeCrm".equals(source)){
                    source = "crm";
                }
                if(StringUtils.isBlank(myDto.getSource())){
                    myDto.setSource(source);
                }
                String code = item.getCode();
                String uncamelCase = StringUtils.uncamelCase(code);
                if(null == joinBusinessType){
                    selectSet.add(source + ".id" );
                    selectSet.add(source + ".id AS 'key'" );
                }
                if("shareType".equals(code)){
                    selectSet.add(source +".share_user_id AS shareUserId");
                    selectSet.add(source +".share_user_name AS shareUserName");
                    selectSet.add(source +".collar_user_id AS collarUserId");
                    selectSet.add(source +".collar_user_name AS collarUserName");
                }
                //替换操作
                if("搜索选择".equals(type) || "查询下拉".equals(type)){
                    String nameField = idFieldToNameField(code);
                    String uncamelCaseName = StringUtils.uncamelCase(nameField);
                    if(StringUtils.isBlank(uncamelCaseName)){
                        uncamelCaseName = uncamelCase;
                    }
                    //市场活动 名称 特殊处理
                    if(code.equals("activityId") && source.equals("business")){
                        selectSet.add("activity.activity_title as "+ nameField);
                    }else{
                        selectSet.add(source +"."+ uncamelCaseName +" as "+ nameField);
                    }
                    selectSet.add(source +"."+ uncamelCase +" as "+ code);
                }else{
                    selectSet.add(source +"."+ uncamelCase +" as "+ code);
                }

                if(valueNotBlank){
                    if("areaId".equals(code)) {
                        whereSet.add(" FIND_IN_SET ("+ value +", crm.area_tree_codes) ");
                    }else if("文本".equals(type) || "区域".equals(type) || "快速文本".equals(type) ){
                        //客户名称 特殊处理
                        if(code.equals("crmName")){
                            whereSet.add("(crm.crm_name LIKE CONCAT('%',#{paramMap.crmName},'%') OR crm.phonetic LIKE CONCAT('%',#{paramMap.crmName},'%'))" );
                        }else{
                            whereSet.add(source +"."+ uncamelCase +" LIKE CONCAT('%',#{paramMap."+code+"},'%')");
                        }
                    }else if("是否".equals(type)) {
                        if("false".equals(value)){
                            whereSet.add("("+source +"."+ uncamelCase +" = '0' OR " +source +"."+ uncamelCase +" IS NULL)");
                        }else{
                            whereSet.add(source +"."+ uncamelCase +" = '1'");
                        }
                    }else if("shareType".equals(code)) {
                        //共享状态
                        if("共享".equals(value)){
                            String shareSql = "( crm.share_type = 1 AND FIND_IN_SET(" + userInfo.getUserId() + ",crm.share_user_id)";
                            //查询分享的模块
                            if(StringUtils.isNotBlank(dynamicDto.getType())){
                                shareSql += " AND  FIND_IN_SET(#{dynamicDto.type},crm.share_menu)";
                            }
                            shareSql += " AND ( crm.share_end = 1 OR crm.share_time > NOW()) )";
                            whereSet.add(shareSql);

                        }else if("未共享".equals(value)){
                            String shareSql = "crm.share_type != 1";
                            whereSet.add(shareSql);
                        }

                    }
                    else if("搜索选择".equals(type)){
                        whereSet.add(source +"."+ uncamelCase +" IN (${paramMap."+code+"})");
                    }
                    else {
                        whereSet.add(source +"."+ uncamelCase +" =  #{paramMap."+code+"}");
                    }
                }else if(("时间".equals(type) ) &&  null != rangDateVal && rangDateVal.length == 2 ){
                    ArrayList rangDate = (ArrayList)rangDateVal[1];
                    String endDate =String.valueOf(rangDate.get(1));
                    String startDate = String.valueOf(rangDate.get(0));
                    if(StringUtils.isNoneBlank(startDate)){
                        whereSet.add(source +"."+ uncamelCase +" >= #{paramMap."+code+"_startDate}");
                    }
                    if(StringUtils.isNoneBlank(endDate)){
                        whereSet.add(source +"."+ uncamelCase +" <  #{paramMap."+code+"_endDate}");
                    }
                }
                else if("日期".equals(type) &&  null != rangDateVal && rangDateVal.length == 2 ){
                    ArrayList rangDate = (ArrayList)rangDateVal[1];
                    String endDate =String.valueOf(rangDate.get(1));
                    String startDate = String.valueOf(rangDate.get(0));
                    if(StringUtils.isNoneBlank(startDate)){
                        whereSet.add(source +"."+ uncamelCase +" >= #{paramMap."+code+"_startDate}");
                    }
                    if(StringUtils.isNoneBlank(endDate)){
                        whereSet.add(source +"."+ uncamelCase +" <=  #{paramMap."+code+"_endDate}");
                    }
                }

            }else if(dataType == 2){
                String source = item.getSource();
                fromTable.add(source);
                if("company".equals(source) || "vendor".equals(source) || "crm".equals(source) ){
                    source = "crm";
                }
                String code = item.getCode();
                Long id = item.getId();
                selectSet.add(source + ".define_fields AS defineFields");
                if(valueNotBlank){
                   if("文本".equals(type) || "区域".equals(type) || "快速文本".equals(type)){
                        whereSet.add(source +".define_fields-> '$.\""+ id +"\"' LIKE CONCAT('%',#{paramMap."+code+"},'%')");
                    }else{
                        whereSet.add(source +".define_fields-> '$.\""+ id +"\"' = #{paramMap."+code+"}");
                    }
                }else if(("时间".equals(type) ) &&  null != rangDateVal && rangDateVal.length == 2 ){
                    ArrayList rangDate = (ArrayList)rangDateVal[1];
                    String endDate =String.valueOf(rangDate.get(1));
                    String startDate = String.valueOf(rangDate.get(0));
                    if(StringUtils.isNoneBlank(startDate)){
                        whereSet.add(source +".define_fields-> '$.\""+ id +"\"' >= #{paramMap."+code+"_startDate}");
                    }
                    if(StringUtils.isNoneBlank(endDate)){
                        whereSet.add(source +".define_fields-> '$.\""+ id +"\"' < #{paramMap."+code+"_endDate}");
                    }
                }
                else if(("日期".equals(type)) &&  null != rangDateVal && rangDateVal.length == 2 ){
                    ArrayList rangDate = (ArrayList)rangDateVal[1];
                    String endDate =String.valueOf(rangDate.get(1));
                    String startDate = String.valueOf(rangDate.get(0));
                    if(StringUtils.isNoneBlank(startDate)){
                        whereSet.add(source +".define_fields-> '$.\""+ id +"\"' >= #{paramMap."+code+"_startDate}");
                    }
                    if(StringUtils.isNoneBlank(endDate)){
                        whereSet.add(source +".define_fields-> '$.\""+ id +"\"' <= #{paramMap."+code+"_endDate}");
                    }
                }
            }
        });


        /** 客户属性 组合*/
        if (StringUtils.isNotBlank(companyType)){
            String companyTypeSql = "";
            boolean isFirst = true;
            if (companyType.contains("isCustomer")){
                companyTypeSql += " crm.is_customer = 1 ";
                isFirst = false;
            }
            if (companyType.contains("isSupplier")){
                if(!isFirst){
                    companyTypeSql += " OR ";
                }
                companyTypeSql += " crm.is_supplier = 1 ";
            }
            if (companyType.contains("isOther")){
                if(!isFirst){
                    companyTypeSql += " OR ";
                }
                companyTypeSql += " crm.is_other = 1 ";
            }
            if (companyType.contains("isFinance")){
                sql.WHERE(" crm.is_finance = 1 ");
            }
            sql.WHERE("(" + companyTypeSql + ")");
        }
        sql.SELECT("crm.is_tasking AS isTasking");
        sql.SELECT("crm.crm_task_id AS crmTaskId");
        /** 主表  + 联合表*/
        if(fromTable.contains("crm")){
            sql.FROM(CUSTOMER_TABLE);
            sql.SELECT(" crm.last_touch_date  AS lastTouchDate");
            sql.SELECT(" crm.last_touch_summary  AS lastTouchSummary");

        }else if(fromTable.contains("linkMan")){
            sql.FROM(LINKMAN_TABLE);
            sql.INNER_JOIN(LINKMAN_TABLE_JOIN);
            sql.SELECT(" linkMan.crm_id  AS crmId");
            sql.SELECT("linkMan.is_tasking AS linkManIsTasking");
            sql.SELECT("linkMan.crm_task_id AS linkManCrmTaskId");

        }else if(fromTable.contains("touch")){
            sql.SELECT( " touch.type as type ");
            Integer touchSearchType = dynamicDto.getTouchSearchType();
            if(null != touchSearchType){
                sql.WHERE(" touch.type = "+ touchSearchType);
            }
            sql.FROM(TOUCH_TABLE);
            sql.INNER_JOIN(TOUCH_TABLE_JOIN);
            if(leftJoinTable.contains("linkMan")){
                sql.LEFT_OUTER_JOIN(TOUCH_LEFT_JOIN_LINKMAN);
            }
            sql.SELECT(" touch.crm_id  AS crmId");

        }
        else if(fromTable.contains("business")){
            sql.FROM(BUSINESS_TABLE);
            sql.INNER_JOIN(BUSINESS_TABLE_JOIN);
            boolean haveCodeSearch = isHaveCodeSearch("activityId", "business", dtos);
            if(haveCodeSearch){
                sql.LEFT_OUTER_JOIN(BUSINESS_JOIN_ACTIVITY);
            }
            sql.SELECT(" business.crm_id  AS crmId");
            sql.SELECT(" business.lose_reason  AS loseReason");
        }
        else  if(fromTable.contains("company")){
            sql.FROM(CUSTOMER_TABLE);
            sql.WHERE(" crm.is_finance = 1 ");
        }
        else if(fromTable.contains("finance")){
            sql.FROM(FINANCE_TABLE);
            sql.INNER_JOIN(FINANCE_TABLE_JOIN);
            sql.SELECT(" finance.crm_id  AS crmId");
        }
        // vendor,other
        else{
            sql.FROM(CUSTOMER_TABLE);
        }
        //是否 关联查询 收藏
        if("isCustomer".equals(companyType)){
            sql.SELECT(" collect.id  AS collectId");
            sql.LEFT_OUTER_JOIN(COLLECT_TABLE_JOIN);
            if(isCollect.size() > 0){
                if(isCollect.get(0)) {
                    sql.WHERE(" collect.id is not null");
                }else {
                    sql.WHERE(" collect.id is null");
                }
            }
        }
        // 基础查询1.状态正常
        sql.WHERE(" crm.status = 0 ");
        // 客户类型范围
        if(StringUtils.isNoneBlank(crmType)){
            sql.WHERE(" crm.crm_type IN (${dynamicDto.crmType}) ");
        }
        // 外呼任务
        if(dynamicDto.getIsNotTasking()){
            sql.WHERE(" crm.is_tasking = 0 ");
        }
        // 指定客户
        if(StringUtils.isNoneBlank(dynamicDto.getCustomerIds())){
            sql.WHERE(" crm.id IN (${dynamicDto.customerIds}) ");
        }
        /** 处理特殊业务 --- 开始*/
        /** 添加 外呼任务明细*/
        if(fromTable.contains("crm") && null != joinBusinessType && 1 == joinBusinessType){
            selectSet.add("crm.id AS crmId");
            selectSet.add("crm.crm_type AS crmType");
            sql.INNER_JOIN(LINKMAN_TABLE + " ON crm.id = linkman.crm_id AND linkman.status = 0 ");
            Integer taskId = dynamicDto.getTaskId();
            String businessSql = "(( crm.is_tasking = 0 ";
            if(null != taskId){
                businessSql += "  OR ( crm.crm_task_id = "+ taskId +" AND linkman.is_tasking = 0 ) ";
            }
            businessSql +="  ) ";
            businessSql += " AND (( crm.crm_type > 0 AND crm.collar_user_id = "+ userInfo.getUserId() +" ) OR crm.crm_type = 0 ))";
            sql.WHERE(businessSql);
            if(null != joinTableConditions && joinTableConditions.size() > 0){
                joinTableConditions.forEach(item->{
                    Object[] rangDateVal = item.getRangDateVal();
                    String value = item.getValue();
                    value = StringUtils.trim(value);
                    boolean valueNotBlank = StringUtils.isNotBlank(value);
                    String type = item.getType();
                    String parentCode = item.getParentCode();
                    String[] split = parentCode.split("_");
                    String table = split[0];
                    String code = split[1];
                    String uncamelCase = StringUtils.uncamelCase(code);
                    selectSet.add(table + ".id" );
                    selectSet.add(table + ".id AS 'key'" );
                    //替换操作
                    if("搜索选择".equals(type) || "查询下拉".equals(type)){
                        String nameField = idFieldToNameField(code);
                        String parentNameField = idFieldToNameField(parentCode);

                        String uncamelCaseName = StringUtils.uncamelCase(nameField);
                        if(StringUtils.isBlank(uncamelCaseName)){
                            uncamelCaseName = uncamelCase;
                        }
                        selectSet.add(table +"."+ uncamelCaseName +" as "+ parentNameField);
                        selectSet.add(table +"."+ uncamelCase +" as "+ parentCode);
                    }else{
                        selectSet.add(table +"."+ uncamelCase +" AS "+ parentCode);
                    }
                    if(valueNotBlank){
                        if("文本".equals(type) || "区域".equals(type)|| "快速文本".equals(type) ){
                            whereSet.add(table +"."+ uncamelCase +" LIKE CONCAT('%',#{paramMap."+parentCode+"},'%')");
                        }else if("是否".equals(type)) {
                            if("false".equals(value)){
                                whereSet.add("("+table +"."+ uncamelCase +" = '0' OR " +table +"."+ uncamelCase +" IS NULL)");
                            }else{
                                whereSet.add(table +"."+ uncamelCase +" = '1'");
                            }
                        }
                        else if("搜索选择".equals(type)){
                            whereSet.add(table +"."+ uncamelCase +" IN (${paramMap."+parentCode+"})");
                        }
                        else{
                            whereSet.add(table +"."+ uncamelCase +" = #{paramMap."+parentCode+"}");
                        }
                    }else if(("时间".equals(type) ) &&  null != rangDateVal && rangDateVal.length == 2 ){
                        ArrayList rangDate = (ArrayList)rangDateVal[1];
                        String startDate = String.valueOf(rangDate.get(0));
                        String endDate =String.valueOf(rangDate.get(1));
                        if(StringUtils.isNoneBlank(startDate)){
                            whereSet.add(table +"."+ uncamelCase +" >= #{paramMap."+parentCode+"_startDate}");
                        }
                        if(StringUtils.isNoneBlank(endDate)){
                            whereSet.add(table +"."+ uncamelCase +" < #{paramMap."+parentCode+"_endDate}");
                        }
                    }
                    else if(("日期".equals(type)) &&  null != rangDateVal && rangDateVal.length == 2 ){
                        ArrayList rangDate = (ArrayList)rangDateVal[1];
                        String startDate = String.valueOf(rangDate.get(0));
                        String endDate =String.valueOf(rangDate.get(1));
                        if(StringUtils.isNoneBlank(startDate)){
                            whereSet.add(table +"."+ uncamelCase +" >= #{paramMap."+parentCode+"_startDate}");
                        }
                        if(StringUtils.isNoneBlank(endDate)){
                            whereSet.add(table +"."+ uncamelCase +" <= #{paramMap."+parentCode+"_endDate}");
                        }
                    }
                });
            }

        }
        /** 处理特殊业务 --- 结束*/

        /** SQL设置 查询字段 */
        sql.SELECT(StringUtils.join(selectSet,","));
        /** SQL设置 查询条件 */
        if(whereSet.size() > 0){
            sql.WHERE(StringUtils.join(whereSet," AND "));
        }
        /** SQL设置 排序 */
        String sortField = dynamicDto.getSortField();
        String sortOrder = dynamicDto.getSortOrder();
        if(StringUtils.isNoneBlank(sortField) && StringUtils.isNoneBlank(sortOrder)){
            String orderType = " DESC";
            if(StringUtils.isNoneBlank(sortOrder) && "ascend".equals(sortOrder)){
                orderType = " ASC";
            }
            sql.ORDER_BY(sortField + orderType);
        }else{
            String source = myDto.getSource();
            switch (source){
                case "crm": sql.ORDER_BY("  crm.create_date DESC");break;
                case "linkMan": sql.ORDER_BY("  linkMan.create_date DESC");break;
                case "touch": sql.ORDER_BY("  touch.contact_date DESC");break;
                case "business": sql.ORDER_BY("  business.create_date DESC");break;
            }
        }
    }

    private String idFieldToNameField(String idFieldTo){
        String result = "";
        if(StringUtils.isNoneBlank(idFieldTo) &&  idFieldTo.endsWith(ID_FIELD)){
            String s = idFieldTo.substring(0, idFieldTo.lastIndexOf(ID_FIELD));
            result = s + NAME_FIELD;
        }
        return result;
    }

    /**
     * 检查 某个字段 开启，且有搜索传值
     * @param code
     * @param source
     * @param dtos
     * @return
     */
    private boolean isHaveCodeSearch(String code,String source,List<DynamicConditionDto> dtos){
        boolean b = dtos.stream().anyMatch(item -> item.getCode().equals(code) && item.getSource().equals(source) && item.getOnOff() && StringUtils.isNotBlank(item.getVal()));
        return b;
    }
//    /**
//     * 批量插入
//     * @author 小啊刚
//     * @date 2020/7/1
//     */
//    public String insertList(List<CrmCustomer> crmCustomerList) {
//        String sql = "INSERT INTO pub_customer ( crm_name, crm_type, crm_no, crm_source, type, company_id, company_name, phonetic, register_capital, area_name, street, phone, email, legal_person, url, crm_grade, enterprise_scale, industry, remarks, create_user_id, create_user_name, define_fields, mobile ) VALUES  ";
//        for(CrmCustomer customer : crmCustomerList) {
//            sql += ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )
//        }
//        return sql;
//    }



}
